package com.hrms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hrms.pojo.AttenManage;
import com.hrms.pojo.SysUser;
import com.hrms.dao.SysUserMapper;
import com.hrms.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrms.utils.MdFive;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.security.SecureRandom;
import java.util.*;

/**
 * 用户表 服务实现类
 *
 * @author LK
 * @since 2021-10-19
 */
@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired(required = false)
	SysUserMapper sysUserMapper;
	//注入加密工具
	@Autowired(required = false)
	private MdFive mdFive;

	@Override
	public HashMap<String, Object> login(SysUser user) {
		HashMap<String, Object> map = new HashMap<>();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getUserPwd());
		Subject sub = SecurityUtils.getSubject();
		try {
			sub.login(token);
			List<SysUser> users = sysUserMapper.selectByName(user.getUserName());
			map.put("info", "登录成功");
			map.put("userId", users.get(0).getUserId());
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			map.put("info", "用户名不正确");
			System.out.println("用户名不正确");
		} catch (IncorrectCredentialsException e) {
			//e.printStackTrace();
			map.put("info", "密码不正确");
			System.out.println("密码不正确");
		}

		return map;
	}

	public HashMap<String, Object> select(SysUser a) {
		HashMap<String, Object> map = new HashMap<>();

		//定义分页对象
		Page<SysUser> page = new Page<>(a.getPage(), a.getRow());
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		//编号查询
		queryWrapper.eq(a.getStaffId() != null, "staff_id", a.getStaffId());
		//Page<AttenManage> aList = attenManageMapper.selectByCon(page, a);

		//用户名的模糊查询
		queryWrapper.like(!StringUtils.isEmpty(a.getUserName()) && a.getUserName() != null, "user_name",
				a.getUserName());
		//查询数据库
		Page<SysUser> aList = sysUserMapper.selectPage(page, queryWrapper);
		//当前页集合
		map.put("list", aList.getRecords());
		//总页数
		map.put("totalPage", aList.getPages());
		//总条数
		map.put("total", aList.getTotal());
		//当前页
		map.put("curPage", a.getPage());
		if (a.getPage() == 1) {
			//上一页
			map.put("prePage", 1);

		} else {
			map.put("prePage", a.getPage() - 1);

		}
		if (a.getPage() == aList.getPages()) {
			//下一页
			map.put("nextPage", aList.getPages());

		} else {
			map.put("nextPage", a.getPage() + 1);

		}
		//每页显示条数
		map.put("row", a.getRow());
		return map;
	}

	@Override
	public List<SysUser> selectByName(String userName) {
		return sysUserMapper.selectByName(userName);
	}

	@Override
	public HashMap<String, Object> add(SysUser a) {
		HashMap<String, Object> map = new HashMap<>();
		SecureRandom random = new SecureRandom();

		//创建条件构造器
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		//定义根据用户名查询的条件
		queryWrapper.eq("user_name", a.getUserName());
		//查询用户名是否重名
		List<SysUser> list = sysUserMapper.selectList(queryWrapper);

		if (list.size() > 0) {
			map.put("info", "用户名重名");
		} else {
			String salt = UUID.randomUUID() + "";
			a.setSalt(salt);
			//生成staffId
			//生成staffId
			StringBuilder str = new StringBuilder();//定义变长字符串
			//随机生成数字，并添加到字符串
			for (int i = 0; i < 7; i++) {
				str.append(random.nextInt(10));
			}
			//将字符串转换为数字并输出
			int password = Integer.parseInt(str.toString());
			a.setStaffId(password);
			//加密密码
			String md5Pass = mdFive.encrypt(a.getUserPwd(), salt);
			a.setUserPwd(md5Pass);
			//新增
			int num = sysUserMapper.insert(a);
			if (num > 0) {
				map.put("info", "保存成功");
			} else {
				map.put("info", "保存失败");
			}
		}
		return map;
	}

	@Override
	public HashMap<String, Object> update(SysUser a) {
		HashMap<String, Object> map = new HashMap<>();

		//创建条件构造器
		QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
		//定义根据用户名查询的条件
		queryWrapper.eq("user_name", a.getUserName());
		//查询用户名是否重名
		List<SysUser> list = sysUserMapper.selectList(queryWrapper);

		if (list.size() > 1) {
			map.put("info", "用户名重名");
		} else {
			String salt = UUID.randomUUID() + "";
			a.setSalt(salt);
			//加密密码
			String md5Pass = mdFive.encrypt(a.getUserPwd(), salt);
			a.setUserPwd(md5Pass);
			//修改
			int num = sysUserMapper.updateById(a);
			if (num > 0) {
				map.put("info", "保存成功");
			} else {
				map.put("info", "保存失败");
			}
		}
		return map;
	}

	@Override
	public HashMap<String, Object> del(Integer a) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		//删除
		int num = sysUserMapper.deleteById(a);
		if (num > 0) {
			map.put("info", "保存成功");
		} else {
			map.put("info", "保存错误");
		}
		return map;
	}

	@Override
	public HashMap<String, Object> updatePwd(SysUser a) {
		HashMap<String, Object> map = new HashMap<>();

		SysUser user = sysUserMapper.selectById(a.getUserId());
		String inputPassword = mdFive.encrypt(a.getUserPwd(), user.getSalt());
		String oldPassword = user.getUserPwd();
		if (!inputPassword.equals(oldPassword) || oldPassword.isEmpty()) {
			map.put("info", "旧密码输入错误！");
			//} else if (a.getNewPwd().isEmpty()) {
			//	map.put("info", "密码不能为空！");
		} else {
			user.setUserPwd(mdFive.encrypt(a.getNewPwd(), user.getSalt()));
			sysUserMapper.updateById(user);
			map.put("info", "修改成功");
		}
		return map;
	}
}
